//
//  BKMyUserFavorStoreController.m
//  bestkeep
//
//  Created by windCould on 16/12/2.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKMyUserFavorStoreController.h"
//#import "BKUserMyFavorCell.h"
#import "BKuserMyFavorEditingCell.h"
#import "BKUserDeleteBtnView.h"
#import "BKMyCommon.h"
#import "BKUserUnitRequestAPI.h"
#import "BKUserCollectionGoodsModel.h"
#import "BKUserRequestResultModel.h"
#import "Mediator+BKGD.h"
#import "BKRefreshGifHeader.h"
#import "BKNewRefreshFooter.h"
#import "PromptTools.h"
#import "BKUserCodeFormat.h"
#import "BKUserMyFavorOrdinaryCell.h"
@interface BKMyUserFavorStoreController ()<UITableViewDelegate,UITableViewDataSource,BKUserDeleteBtnViewDelegate,UIActionSheetDelegate,BKuserMyFavorEditingCellDelegate>

@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)NSMutableArray * dateArr;
@property (nonatomic,strong)BKUserDeleteBtnView * deleteView;
@property (nonatomic,assign)BOOL  isDealWithData;
@property (nonatomic,strong)UITableView * tableview;
@property (nonatomic,strong)UIButton * editBtn;
@property (nonatomic,strong)BKUserCollectionGoodsModel * favorGoodsModel;
@property (nonatomic,strong)NSMutableArray * deletIndexArr;
@property (nonatomic,strong) ExceptionView *exceptionView;
@property (nonatomic,copy)NSString * curPage;
@property (nonatomic,copy)NSString * totalPage;

@property (nonatomic,strong)NSMutableArray * requestDataArr;


@end


@implementation BKMyUserFavorStoreController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = ThemeBackgroundColor;
    self.navigationItem.title = BKMyLocalizedString(@"BKUserMyFavorite");
    self.edgesForExtendedLayout = UIRectEdgeNone;
    _deletIndexArr = [NSMutableArray new];
    [self setUpViews];
    [self addRefresh];
   // [self loadData];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadData];

}

#pragma mark =========================Function=================================

-(void)editBtn:(UIButton *)btn
{
    if (btn.isSelected) {
        
        [btn setSelected:NO];
        self.isDealWithData = NO;
        for (NSString *  indexStr in _deletIndexArr) {
            
            if (self.dateArr.count > [indexStr integerValue]) {
                
                BKUserMyFavorGoodsModel * model = self.dateArr[[indexStr integerValue]];
                model.isSelect = NO;
            }
        }
        
        _deletIndexArr = [NSMutableArray new];
        
    } else {
    
        [btn setSelected:YES];
        self.isDealWithData = YES;
    }
    
    [self.tableView reloadData];
}
-(void)loadData
{
    [self loadCollectionGoodsListWithPageSize:20 page:1];
}

#pragma mark =========================BKuserMyFavorEditingCellDelegate=======

-(void)bkUserMyFavorEditingCell:(BKuserMyFavorEditingCell *)bkUserMyFavorEditingCell clickCellIndex:(NSInteger)index deleteOrNo:(BOOL)isDelete
{
    
    if (index < self.dateArr.count) {
        
        BKUserMyFavorGoodsModel * model = self.dateArr[index];
        model.isSelect = isDelete;
        [self.tableView  reloadData];
    }
    
    NSString * indexStr = [NSString stringWithFormat:@"%ld",(long)index];
    if (isDelete) {
        
        [_deletIndexArr addObject:indexStr];
    } else {
    
        for (NSString * str  in _deletIndexArr) {
            
            if ([str isEqualToString:indexStr]) {
                
                [_deletIndexArr removeObject:indexStr];
                break;
            }
        }
    }
   
}

#pragma mark =========================BKUserDeleteBtnViewDelegate============

-(void)bkUserDeleteBtnView:(BKUserDeleteBtnView *)bkUserDeleteBtnView deleteBtnClick:(id)parameter
{
   NSUInteger num = _deletIndexArr.count;
    
    if (num == 0) {
        
        [HUD showMessage:@"您还没有选择要取消收藏的商品"];
        return;
    }
    
    NSString * deleTipStr = [NSString stringWithFormat:@"确定取消%lu件收藏商品",(unsigned long)num];
    UIActionSheet * actionSheeet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:deleTipStr otherButtonTitles:nil, nil];
    [actionSheeet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
        NSMutableArray * temArr = [NSMutableArray array];
        NSMutableArray * temArr2 = [NSMutableArray array];
        for (NSString * indx in _deletIndexArr) {
            
            BKUserMyFavorGoodsModel * favorModel = self.dateArr[[indx intValue]];
            [temArr addObject:favorModel.collect_id];
            [temArr2 addObject:favorModel];
        }
        
        [self deleteCollectionGoodsWithCollectionId:temArr resultBlock:^(id obj, NSError *error) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                for (BKUserMyFavorGoodsModel * temModel in temArr2) {
                   
                    for (BKUserMyFavorGoodsModel * collectModel in self.dateArr) {
                        
                        if ([temModel.collect_id isEqualToString:collectModel.collect_id]) {
                            
                               [self.dateArr removeObject:temModel];
                               break;
                        }
                        
                    }
                }
                
                [_deletIndexArr removeAllObjects];
                self.dateArr = _dateArr;
                self.isDealWithData = NO;
                [self loadData];
                NSLog(@"删除成功＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝");
                [HUD showSuccessMessage:@"取消成功"];
            } else {
            
                NSLog(@"%@",result.msg);
                [HUD showErrorMessage:result.msg];
            }
        }];
        
       
    }
}


#pragma mark =========================UITableViewDelegate====================

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [_dateArr count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BKUserMyFavorGoodsModel * favorModel = _dateArr[indexPath.row];
    if (_isDealWithData) {
        
        BKuserMyFavorEditingCell * cell = [BKuserMyFavorEditingCell cellWithTableview:tableView];
        cell.favorGoodsModel = favorModel;
        cell.myDelegate = self;
        cell.indexRow = indexPath.row;
        return cell;
    } else {
    
        BKUserMyFavorOrdinaryCell * cell = [BKUserMyFavorOrdinaryCell cellWithTableview:tableView];
        cell.favorGoodsModel = favorModel;
        return cell;
    }
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 
    return !_isDealWithData;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return @"取消收藏";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        BKUserMyFavorGoodsModel * myFavorModel = self.dateArr[indexPath.row];
        [BKIndicationView showInView:self.view];
        [BKUserUnitRequestAPI deleteCollectionGoodsFromListWithCollectionId:myFavorModel.collect_id completeBlock:^(id obj, NSError *error) {
            [BKIndicationView dismiss];
            if (obj) {
                
                BKUserRequestResultModel * result = obj;
                if ([result.success isEqualToString:@"1"]) {
                    
                    [self.dateArr removeObjectAtIndex:indexPath.row];
                     self.dateArr = self.dateArr;
                     self.isDealWithData = NO;
                    [self loadData];
                    NSLog(@"%@",result.msg);
                    [HUD showSuccessMessage:@"取消成功"];
                } else {
                
                    NSLog(@"%@",result.msg);
                    [HUD showErrorMessage:result.msg];
                }
            } else {
                
                NSLog(@"删除失败！");
                if (error.code==502) {
                    [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
                }else{
                    [HUD showErrorMessage:error.localizedDescription];
                }
            }
            
        }];
  }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!_isDealWithData) {
        
        BKUserMyFavorGoodsModel * myFavorModel = self.dateArr[indexPath.row];
        UIViewController * targetVc = [[Mediator sharedInstance]BKGD_goodsDetailViewController:myFavorModel.goods_id saleTypes:nil];
        [self.navigationController pushViewController:targetVc animated:YES];
    }
}

#pragma mark =========================NetWorkRequest===================================

//获取用户收藏列表
-(void)loadCollectionGoodsListWithPageSize:(NSInteger)pagesize page:(NSInteger)pageNo
{
    if(self.exceptionView) {
        
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    
    __weak typeof(self) weakSelf = self;
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI getUserCollectionListWithPageSize:pagesize pageNo:pageNo completeBlock:^(id obj, NSError *error){
       // [weakSelf.tableView.mj_header endRefreshing];
        [BKIndicationView dismiss];
      
        if (obj) {
            
            weakSelf.favorGoodsModel = obj;
            weakSelf.curPage =  [NSString stringWithFormat:@"%@",weakSelf.favorGoodsModel.pageNo];
            weakSelf.totalPage = [NSString stringWithFormat:@"%@",weakSelf.favorGoodsModel.total];
            weakSelf.requestDataArr = [NSMutableArray arrayWithArray:weakSelf.favorGoodsModel.list];
            if (weakSelf.favorGoodsModel.list.count == [weakSelf.totalPage integerValue]) {
                
                self.tableView.tableFooterView = [[UIView alloc]init];
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                weakSelf.tableView.mj_footer = nil;
                
            } else {
            
                [weakSelf.tableView.mj_footer  endRefreshing];
            }
            
            if (weakSelf.favorGoodsModel.list.count == 0) {
                
                weakSelf.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeEmptyPages];
                ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeEmptyPages handler:^(ExceptionViewAction *action) {
                    
                    [weakSelf loadData];
                }];
                weakSelf.exceptionView.contentLabel.text = @"暂无收藏商品";
                [self.exceptionView addAction:retryAction];
                
                [self.exceptionView showInView:self.view];
                weakSelf.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height + 64);
            }
            
            
        } else {
        
            if(!self.exceptionView && error) {
                
                ExceptionCodeType errorType = ExceptionCodeTypeRequestFailed;
                if (error.code == -1009) {
                    errorType = ExceptionCodeTypeNoNetwork;
                }else if (error.code == -1001){
                    errorType = ExceptionCodeTypeRequestFailed;
                }else if (error.code == 502 || error.code == 404){
                    errorType = ExceptionCodeTypeServerError;
                }else{
                    errorType = ExceptionCodeTypeFailedToLoad;
                }
                
                weakSelf.exceptionView = [ExceptionView exceptionViewWithType:errorType];
                ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                    
                    [weakSelf loadData];
                }];
                [self.exceptionView addAction:retryAction];
                
                [self.exceptionView showInView:self.view];
                weakSelf.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height + 64);
                NSLog(@"用户收藏列表请求失败。。。。。。。。。。");
         }
        }
    }];
    
}

//下拉加刷新
-(void)loadNewCollectionListWithPageSize:(NSInteger)pagesize pageNo:(NSInteger)pageNo
{
    __weak typeof(self) weakSelf = self;
    [weakSelf.tableView.mj_footer endRefreshing];
    [BKUserUnitRequestAPI getUserCollectionListWithPageSize:pagesize pageNo:pageNo completeBlock:^(id obj, NSError *error){
        [weakSelf.tableView.mj_header endRefreshing];
        if (obj) {
            
            BKUserCollectionGoodsModel * collecModel = obj;
            weakSelf.curPage =  [NSString stringWithFormat:@"%@",collecModel.pageNo];
            weakSelf.totalPage = [NSString stringWithFormat:@"%@",collecModel.total];
            self.requestDataArr = [NSMutableArray arrayWithArray:collecModel.list];
        } else {
            
            [HUD showErrorMessage:@"网络数据请求失败"];
            NSLog(@"用户收藏列表请求失败。。。。。。。。。。");
        }
    }];

}

//删除单个收藏商品
-(void)deleteCollectionGoodsWithCollectionId:(NSArray *)collectionIds resultBlock:(BKUserCompleteBlock)resultBlock
{
    NSString * collectionId ;
    if (collectionIds.count == 1) {
        
        collectionId = collectionIds[0];
    } else {
    
        collectionId = [collectionIds componentsJoinedByString:@","];
    }
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI deleteCollectionGoodsFromListWithCollectionId:collectionId completeBlock:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                [HUD showSuccessMessage:@"取消成功"];
            } else {
            
                [HUD showErrorMessage:result.msg];
            }
            
            resultBlock(result,nil);
            
        } else {
            if (error.code==502) {
                [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
            }else{
                [HUD showErrorMessage:error.localizedDescription];
            }
            NSLog(@"请求失败！");
        }
        
    }];
}

#pragma mark =========================赋值方法===================================
-(void)setFavorGoodsModel:(BKUserCollectionGoodsModel *)favorGoodsModel
{
    _favorGoodsModel = favorGoodsModel;
    self.dateArr = _favorGoodsModel.list;
}

-(void)setRequestDataArr:(NSMutableArray *)requestDataArr
{
    _requestDataArr = requestDataArr;
    self.dateArr = _requestDataArr;
}


-(void)setDateArr:(NSMutableArray *)dateArr
{
    _dateArr = dateArr;
    if (_dateArr.count == 0 ||_dateArr == nil) {
        
        _editBtn.hidden = YES;
    } else {
    
        _editBtn.hidden = NO;
    }

    
    [self.tableView reloadData];
}

-(void)setIsDealWithData:(BOOL)isDealWithData
{
    _isDealWithData = isDealWithData;
    if (_isDealWithData) {
        
        _deleteView.hidden = NO;
        _editBtn.selected = YES;
        [self layoutViewsIsDeleteState:YES];
    } else {
    
        _deleteView.hidden = YES;
        _editBtn.selected = NO;
        [self layoutViewsIsDeleteState:NO];
    }
    
    [self.tableView  reloadData];
}

-(void)addRefresh
{
    //BKRefreshGifHeader *headerRefresh = [BKRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    //self.tableView.mj_header = headerRefresh;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
    footer.hidden = YES;
    footer.stateLabel.textColor = LoadMoreDataTitleColor;
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color = IndictorViewColor;
    [footer addSubview:loadingView];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.automaticallyHidden = YES;
}

-(void)updateMore
{
    if ([self.curPage integerValue] > [self.totalPage integerValue]/20) {
        
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
       // [self.tableView.mj_footer endRefreshing];
              return ;
    }
    
    NSInteger  pageRequest = [self.curPage integerValue];
    [self loadMorDataWithPageSize:20 loadPage:pageRequest +1];
}


-(void)refreshData
{
    [self loadNewCollectionListWithPageSize:20 pageNo:1];
}

-(void)loadMorDataWithPageSize:(NSInteger)pageSize loadPage:(NSInteger)page
{
    [self.tableView.mj_header endRefreshing];
    __weak typeof(self) weakSelf = self;
    
    [BKUserUnitRequestAPI getUserCollectionListWithPageSize:pageSize pageNo:page completeBlock:^(id obj, NSError *error){
    
        if (obj) {
            
            BKUserCollectionGoodsModel * collectionModel = obj;
            weakSelf.curPage =  [NSString stringWithFormat:@"%@",collectionModel.pageNo];
            weakSelf.totalPage = [NSString stringWithFormat:@"%@",collectionModel.total];
            [self.requestDataArr addObjectsFromArray:collectionModel.list];
            if (self.requestDataArr.count == [weakSelf.totalPage integerValue]) {
                
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                weakSelf.tableView.mj_footer = nil;
                self.tableView.tableFooterView = [PromptTools getViewWhenDataEndLoading];
            } else {
                
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            self.requestDataArr = self.requestDataArr;
            
        } else {
            
            [weakSelf.tableView.mj_footer endRefreshing];            //[HUD showErrorMessage:error.localizedDescription];
            [BKShowBottomTiPMessageView showMessage:error.localizedDescription];
            NSLog(@"用户收藏列表请求失败。。。。。。。。。。");
        }
        
    }];
    
}

#pragma mark =========================布局======================================

-(void)setUpViews
{
    _isDealWithData = NO;
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableView];
    
    _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _editBtn.frame = CGRectMake(0, 0, 50, 45);
    _editBtn.selected = NO;
    _editBtn.hidden = YES;
    _editBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    _editBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_editBtn setTitle:@"完成" forState:UIControlStateSelected];
    [_editBtn addTarget:self action:@selector(editBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_editBtn setTitleColor:BK_MY_COLOR_05 forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_editBtn];
    
    _deleteView = [[BKUserDeleteBtnView alloc]initWithFrame:CGRectZero];
    _deleteView.hidden = YES;
    _deleteView.myDelegate = self;
    [self.view addSubview: _deleteView];
    [self layoutViewsIsDeleteState:NO];
}

-(void)layoutViewsIsDeleteState:(BOOL)isDelete
{
    
    if (isDelete) {
        
       [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
           
           make.top.mas_equalTo(self.view.mas_top).offset(0);
           make.left.mas_equalTo(self.view.mas_left).offset(0);
           make.right.mas_equalTo(self.view.mas_right).offset(0);
           make.bottom.mas_equalTo(self.view.mas_bottom).offset(-49);
       }];
       
        self.deleteView.frame = CGRectMake(0, self.view.bounds.size.height-49, self.view.bounds.size.width, 49);
        
    } else {
    
       [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
           
           make.top.mas_equalTo(self.view.mas_top).offset(0);
           make.left.mas_equalTo(self.view.mas_left).offset(0);
           make.right.mas_equalTo(self.view.mas_right).offset(0);
           make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
           
       }];

    }
}

@end
